<template>
	<view v-if="visible" class="custom-preview" @click="closePreview">
		<swiper class="preview-swiper" :current="currentIndex" @change="swiperChange">
			<swiper-item v-for="(url, index) in urls" :key="index">
				<view class="image-container">
					<image :src="url" mode="aspectFit" class="preview-image" :style="{ transform: `scale(${scale})` }"
						@click.stop="handleImageClick" @touchstart="handleTouchStart" @touchmove="handleTouchMove"
						@touchend="handleTouchEnd" />
				</view>
			</swiper-item>
		</swiper>
		<view class="indicator">
			{{ currentIndex + 1 }} / {{ urls.length }}
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';

	const props = defineProps({
		visible: Boolean,
		urls: Array,
		currentIndex: Number
	});

	const emit = defineEmits(['close', 'index-change']);

	const scale = ref(1);
	const lastTouchTime = ref(0);
	const lastDistance = ref(0);

	function closePreview() {
		scale.value = 1;
		emit('close');
	}

	function swiperChange(e) {
		scale.value = 1;
		emit('index-change', e.detail.current);
	}

	function handleImageClick() {
		const now = Date.now();
		if (now - lastTouchTime.value < 300) {
			// 双击放大/缩小
			scale.value = scale.value === 1 ? 2 : 1;
		}
		lastTouchTime.value = now;
	}

	function handleTouchStart(e) {
		if (e.touches.length === 2) {
			lastDistance.value = getDistance(e.touches[0], e.touches[1]);
		}
	}

	function handleTouchMove(e) {
		if (e.touches.length === 2) {
			const currentDistance = getDistance(e.touches[0], e.touches[1]);
			const diff = currentDistance - lastDistance.value;

			// 双指缩放
			scale.value = Math.max(1, Math.min(3, scale.value + diff * 0.01));
			lastDistance.value = currentDistance;
		}
	}

	function handleTouchEnd() {
		lastDistance.value = 0;
	}

	function getDistance(touch1, touch2) {
		const dx = touch1.clientX - touch2.clientX;
		const dy = touch1.clientY - touch2.clientY;
		return Math.sqrt(dx * dx + dy * dy);
	}
</script>

<style scoped>
	.custom-preview {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.95);
		z-index: 9999;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.preview-swiper {
		width: 100%;
		height: 100%;
	}

	.image-container {
		width: 100%;
		height: 100%;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.preview-image {
		max-width: 100%;
		max-height: 100%;
		transition: transform 0.3s ease;
	}

	.indicator {
		position: absolute;
		top: 40px;
		right: 20px;
		background-color: rgba(0, 0, 0, 0.5);
		color: white;
		padding: 5px 10px;
		border-radius: 10px;
		font-size: 14px;
	}
</style>